$(document).ready(function () {
  // 点击a标签 修改样式
  $(".sort").on("click", "a", function (e) {
    e.preventDefault();
    $(this).addClass("cur").siblings().removeClass("cur");
    searchWorks();
  });
  // 点击分类 显示小分类列表
  $(".book_type").on("click", "a", function (e) {
    e.preventDefault();
    let majorId = $(this).attr("value");
    getMinorList(majorId);
  });

  getAllMajorList();
  searchWorks();
});

// 获取大分类详情
function getAllMajorList() {
  $.ajax({
    type: "POST",
    url: "AllMajorList.do",
    dataType: "json",
    success: function (data) {
      let major = data.data;
      // 标签
      for (data of major) {
        let a = `<a href="" value="${data.majorId}">${data.majorName}</a>`;
        $(".book_type").append(a);
      }
    },
  });
}

// 获取详细分类列表
function getMinorList(majorId) {
  $.ajax({
    type: "POST",
    url: "MinorList.do",
    data: { majorId: majorId },
    dataType: "json",
    success: function (data) {
      let minorList = data.data;
      const $ul = $(".sort .li_ul");
      $ul.empty();
      for (data of minorList) {
        let li = `<li><a href="" value="${data.minorId}">${data.minorName}</a><li>`;
        $(".li_ul").append(li);
      }
      // 如果没有内容就隐藏
      if ($ul.children().length === 0) {
        $ul.hide();
      } else {
        $ul.show();
      }
    },
  });
}

function searchWorks() {
  // 初始化工作查询对象
  const workQueryDTO = {
    pageNum: 1,
    pageSize: 10,
  };

  // 获取大分类ID
  const $selectedMajor = $(".book_type a.cur");
  if ($selectedMajor.length > 0) {
    workQueryDTO.majorCategoryId = $selectedMajor.attr("value");
  }

  // 获取小分类ID
  const $selectedMinor = $(".li_ul a.cur");
  if ($selectedMinor.length > 0) {
    workQueryDTO.minorCategoryId = $selectedMinor.attr("value");
  }

  // 获取频道筛选
  const $selectedGender = $(".gender a.cur");
  if ($selectedGender.length > 0) {
    workQueryDTO.gender = $selectedGender.attr("value");
  }

  // 获取字数筛选
  const $selectedWordCount = $(".wordCount a.cur");
  if ($selectedWordCount.length > 0) {
    const wordCountFilter = $selectedWordCount.attr("value");
    if (wordCountFilter) {
      // 解析范围值（如"0-3e5"拆分为0和300000）
      const [minStr, maxStr] = wordCountFilter.split("-");
      workQueryDTO.wordCountMin = parseWordCount(minStr);
      workQueryDTO.wordCountMax = parseWordCount(maxStr);
    }
  }

  // 获取更新时间筛选
  const $selectedUpdateTime = $(".updateTime a.cur");
  if ($selectedUpdateTime.length > 0) {
    workQueryDTO.updateTime = $selectedUpdateTime.attr("value");
  }

  // 获取完结状态筛选
  const $selectedIsEnd = $(".isEnd a.cur");
  if ($selectedIsEnd.length > 0) {
    workQueryDTO.isFinished = $selectedIsEnd.attr("value");
  }

  // 移除所有null和空字符串字段
  for (const key in workQueryDTO) {
    if (workQueryDTO[key] === null || workQueryDTO[key] === "") {
      delete workQueryDTO[key];
    }
  }

  console.log(workQueryDTO);
  const $bookList = $(".book-list");
  $.ajax({
    url: "selectBookByConditions.do",
    type: "POST",
    contentType: "application/json",
    data: JSON.stringify(workQueryDTO),
    success: function (data) {
      // 清空列表
      $bookList.empty();

      let bookData = data.data.data;
      console.log(bookData);

      if (bookData != null && bookData.length > 0) {
        $.each(bookData, function (index, book) {
          // 创建列表项元素
          const $li = $("<li></li>");

          // 设置列表项HTML内容
          $li.html(`<div class="pic">
                            <a href="read.html?bookId=${book.bookId}">
                                <img src="${book.coverUrl}" alt="">
                            </a>
                        </div>
                        <div class="txt">
                            <span class="data-list-title">
                                <a href="">${book.bookName}</a>
                            </span>
                            <span class="tags">
                                <em>${book.bookType}</em>
                                &nbsp;&nbsp;&nbsp;&nbsp
                                ${book.bookState}
                                &nbsp;&nbsp;&nbsp;&nbsp;${formatWordCount(
                                  book.wordCount
                                )}
                            </span>
                            <span class="des omit">
                                ${book.bookIntroduction}
                            </span>
                            <span class="author_name">
                            ${book.bookWriter}&nbsp;&nbsp;
                            ${parseLocalDateTime(book.updateTime)}更新</span>
                        </div>`);
          // 添加到列表容器
          $bookList.append($li);
        });
      }
    },
    error: function (error) {
      console.error("请求失败:", error);
    },
  });
}

// 格式化日期时间
function parseLocalDateTime(json) {
  // 提取年、月、日
  const year = json.year;
  const month = String(json.monthValue).padStart(2, "0");
  const day = String(json.dayOfMonth).padStart(2, "0");

  // 返回 yy-mm-dd 格式
  return `${year}-${month}-${day}`;
}

// 格式化字数
function formatWordCount(count) {
  if (!count || count < 10000) {
    return count + "字";
  }
  return (count / 10000).toFixed(2) + "万字";
}
